<!-- 商品发布页面 -->
<template>
    <div class="publish-product">
        <el-card class="form-card">
            <template #header>
                <div class="card-header">
                    <h2>发布商品</h2>
                </div>
            </template>

            <el-form ref="formRef" :model="formData" :rules="rules" label-width="100px" class="product-form">
                <!-- 基本信息 -->
                <el-form-item label="商品名称" prop="name">
                    <el-input v-model="formData.name" placeholder="请输入商品名称" />
                </el-form-item>

                <el-form-item label="商品分类" prop="categoryId">
                    <el-select v-model="formData.categoryId" placeholder="请选择商品分类">
                        <el-option 
                            v-for="category in categories" 
                            :key="category.id" 
                            :label="category.name" 
                            :value="category.id" 
                        />
                    </el-select>
                </el-form-item>

                <el-form-item label="商品价格" prop="price">
                    <el-input-number v-model="formData.price" :min="0" :precision="2" :step="0.1" />
                </el-form-item>
                
                <el-form-item label="商品成色" prop="condition">
                    <el-select v-model="formData.condition" placeholder="请选择商品成色">
                        <el-option label="全新" value="全新" />
                        <el-option label="9成新" value="9成新" />
                        <el-option label="8成新" value="8成新" />
                        <el-option label="7成新" value="7成新" />
                        <el-option label="6成新及以下" value="6成新及以下" />
                    </el-select>
                </el-form-item>

                <el-form-item label="商品描述" prop="description">
                    <el-input v-model="formData.description" type="textarea" rows="4"
                        placeholder="请详细描述商品的成色、使用年限、配件等信息" />
                </el-form-item>

                <!-- 图片上传 -->
                <el-form-item label="商品图片" prop="imageUrls">
                    <el-upload v-model:file-list="fileList" action="#" list-type="picture-card"
                        :auto-upload="false"
                        :on-preview="handlePictureCardPreview" :on-remove="handleRemove" 
                        :before-upload="beforeUpload">
                        <el-icon>
                            <Plus />
                        </el-icon>
                    </el-upload>

                    <el-dialog v-model="dialogVisible">
                        <img w-full :src="dialogImageUrl" alt="Preview Image" />
                    </el-dialog>
                </el-form-item>

                <!-- 位置信息 -->
                <el-form-item label="交易位置" prop="location">
                    <div class="location-wrapper">
                        <location-search v-model="searchAddress" @select="handleLocationSelect" class="mb-4" />
                        <location-picker v-model="formData.location" @change="handleLocationChange" height="300px" />
                    </div>
                </el-form-item>

                <!-- 提交按钮 -->
                <el-form-item>
                    <el-button type="primary" @click="handleSubmit" :loading="submitting">发布商品</el-button>
                    <el-button @click="handleReset">重置</el-button>
                </el-form-item>
            </el-form>
        </el-card>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { Plus } from '@element-plus/icons-vue'
import type { FormInstance, UploadProps } from 'element-plus'
import { LocationPicker, LocationSearch } from '@/components/map'
import request from '@/utils/request' // 导入request工具
import { ElMessage } from 'element-plus' // 导入ElMessage

const router = useRouter()
const submitting = ref(false)

// 商品分类数据
const categories = ref([])

// 表单数据
const formData = ref({
    name: '',
    categoryId: '',
    price: 0,
    description: '',
    imageUrls: [] as string[],
    condition: '全新',
    location: [116.397428, 39.90923] as [number, number],
    address: null as any
})

// 表单验证规则
const rules = {
    name: [
        { required: true, message: '请输入商品名称', trigger: 'blur' },
        { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
    ],
    categoryId: [
        { required: true, message: '请选择商品分类', trigger: 'change' }
    ],
    price: [
        { required: true, message: '请输入商品价格', trigger: 'blur' },
        { type: 'number', min: 0, message: '价格必须大于 0', trigger: 'blur' }
    ],
    condition: [
        { required: true, message: '请选择商品成色', trigger: 'change' }
    ],
    description: [
        { required: true, message: '请输入商品描述', trigger: 'blur' },
        { min: 10, max: 500, message: '长度在 10 到 500 个字符', trigger: 'blur' }
    ],
    imageUrls: [
        { required: true, message: '请上传至少一张商品图片', trigger: 'change' },
        { type: 'array', min: 1, max: 9, message: '请上传 1-9 张商品图片', trigger: 'change' }
    ],
    location: [
        { required: true, message: '请选择交易位置', trigger: 'change' }
    ]
}

// 图片上传相关
const fileList = ref<UploadProps['fileList']>([])
const dialogImageUrl = ref('')
const dialogVisible = ref(false)

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
    console.log(uploadFile, uploadFiles)
    // 更新文件列表
    fileList.value = uploadFiles
}

const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
    dialogImageUrl.value = URL.createObjectURL(uploadFile.raw)
    dialogVisible.value = true
}

const beforeUpload: UploadProps['beforeUpload'] = (file) => {
    const isImage = /^image\//.test(file.type)
    const isLt2M = file.size / 1024 / 1024 < 2

    if (!isImage) {
        ElMessage.error('只能上传图片文件!')
        return false
    }
    if (!isLt2M) {
        ElMessage.error('图片大小不能超过 2MB!')
        return false
    }
    return true
}

// 位置选择相关
const searchAddress = ref('')

const handleLocationSelect = (item: any) => {
    formData.value.location = [item.location.lng, item.location.lat]
    formData.value.address = item
}

const handleLocationChange = ({ location, address }: any) => {
    formData.value.location = location
    formData.value.address = address
}

// 获取商品分类
const fetchCategories = async () => {
    try {
        const response = await request.get('/products/categories')
        if (response && response.code === 200) {
            categories.value = response.data || []
        } else {
            ElMessage.warning('获取分类数据失败，请刷新重试')
            // 使用默认分类数据
            categories.value = [
                { id: 1, name: '数码电子' },
                { id: 2, name: '图书教材' },
                { id: 3, name: '生活用品' },
                { id: 4, name: '服装鞋帽' },
                { id: 5, name: '运动户外' },
                { id: 6, name: '其他' }
            ]
        }
    } catch (error) {
        console.error('获取分类失败:', error)
        // 使用默认分类数据
        categories.value = [
            { id: 1, name: '数码电子' },
            { id: 2, name: '图书教材' },
            { id: 3, name: '生活用品' },
            { id: 4, name: '服装鞋帽' },
            { id: 5, name: '运动户外' },
            { id: 6, name: '其他' }
        ]
    }
}

// 表单操作
const formRef = ref<FormInstance>()

// 创建商品的API函数
const createProduct = async (productData: any, files: any[]) => {
    try {
        // 从localStorage获取用户信息
        const userInfo = localStorage.getItem('userInfo')
        if (!userInfo) {
            ElMessage.error('用户未登录，请先登录')
            return false
        }
        
        // 创建FormData对象
        const formData = new FormData()
        
        // 添加商品基本信息
        formData.append('name', productData.name)
        formData.append('price', String(productData.price))
        formData.append('description', productData.description)
        formData.append('condition', productData.condition)
        formData.append('categoryId', String(productData.categoryId))
        formData.append('longitude', String(productData.location[0]))
        formData.append('latitude', String(productData.location[1]))
        formData.append('locationDescription', productData.address ? productData.address.address : '未指定位置')
        
        // 添加图片文件
        for (let i = 0; i < files.length; i++) {
            formData.append('files', files[i].raw)
        }
        
        // 发送请求创建商品
        const response = await request.post('/products', formData, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        })
        
        if (response.code === 200) {
            ElMessage.success('商品发布成功')
            return {
                success: true,
                productId: response.data // 假设后端返回了新创建的商品ID
            }
        } else {
            ElMessage.error(response.message || '发布失败，请稍后重试')
            return { success: false }
        }
    } catch (error) {
        console.error('发布商品失败:', error)
        ElMessage.error('发布失败，请稍后重试')
        return { success: false }
    }
}

const handleSubmit = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid, fields) => {
        if (valid) {
            // 检查是否有上传的图片文件
            if (fileList.value.length === 0) {
                ElMessage.error('请上传至少一张商品图片')
                return
            }
            
            submitting.value = true
            
            try {
                // 调用API发布商品
                const result = await createProduct(formData.value, fileList.value)
                if (result.success) {
                    // 发布成功，重置表单
                    handleReset()
                    // 提示用户发布成功后，跳转到商品详情页或商品列表页
                    setTimeout(() => {
                        if (result.productId) {
                            router.push(`/product/${result.productId}`)
                        } else {
                            router.push('/user/center?menu=products') // 跳转到用户中心的商品管理页
                        }
                    }, 1500)
                }
            } finally {
                submitting.value = false
            }
        } else {
            console.error('表单验证失败:', fields)
            ElMessage.error('请完善商品信息')
        }
    })
}

const handleReset = () => {
    if (!formRef.value) return
    formRef.value.resetFields()
    formData.value.imageUrls = []
    fileList.value = []
}

onMounted(() => {
    // 加载分类数据
    fetchCategories()
})
</script>

<style scoped>
.publish-product {
    max-width: 1200px;
    margin: 20px auto;
    padding: 0 20px;
}

.form-card {
    margin-bottom: 20px;
}

.card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
}

.product-form {
    margin-top: 20px;
}

.location-wrapper {
    display: flex;
    flex-direction: column;
    gap: 16px;
}

.mb-4 {
    margin-bottom: 16px;
}
</style>